package com.example.demo;

import com.example.demo.DAO.UserDAO;
import com.example.demo.Entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入UserServlet的doGet方法");
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求字符编码
        System.out.println("进入UserServlet");
        request.setCharacterEncoding("UTF-8");
        // 设置响应字符编码
        response.setContentType("text/html;charset=UTF-8");
        // 获取响应字符输出流
        PrintWriter out = response.getWriter();
        // 获取操作类型
            String type = request.getParameter("type");
        if("login".equals(type)){
            // 获取用户登录信息（用户名和密码）
            String userLoginName= request.getParameter("userLoginName");
            String userPwd = request.getParameter("userPwd");
            // 从请求中获取用户提交的验证码
            String userCode = request.getParameter("validateCode");
            // 获取本次请求会话中保存的验证码
            String validateCode = (String)request.getSession().getAttribute("validateCode");
            // 判断验证码是否一致，若验证码不一致，提示错误，返回登陆页面
            if( validateCode == null    ||  !validateCode.equals(userCode)){
                out.print("<script type='text/javascript'>");
                out.print("alert('验证码输入错误！');");
                out.print("window.location='login.html';");
                out.print("</script>");
                return ;
            }

            // 根据用户名和密码进行用户登录判断
            if (userLoginName== null || userLoginName.trim().isEmpty() ||
                    userPwd == null || userPwd.trim().isEmpty()) {
                out.print("<script>alert('用户名和密码不能为空！');history.back();</script>");
                return;
            }
            UserDAO dao = new UserDAO();
            User user = dao.login(userLoginName,userPwd);
            if(user != null){
                // 登陆成功，使用会话域属性记录用户信息，
                // 重定向到管理主界面
                HttpSession session = request.getSession();
                //这里登录的时候设置的session,为了后边getAttribute的时候拿到
                session.setAttribute("user", user);
                // 使用重定向的方法，跳转到管理主界面（main.html）
                response.sendRedirect("manage/main.html");
            }else{
                // 登录失败，错误信息提示，返回登录页面
                out.print("<script type='text/javascript'>");
                out.print("alert('用户名或密码错误，请重新输入！');");
                out.print("window.location='login.html';");
                out.print("</script>");
            }
        } else if ("logout".equals(type)) {
            // 用户本次会话失效(让session 失效)
            System.out.println("退出啦");
            HttpSession session = request.getSession();
            session.invalidate();
            request.getSession(true);
            // 返回登陆页面
            out.print("<script type='text/javascript'>");
            out.print("window.location='login.html';");
            out.print("</script>");
        }else if("updateSelect".equals(type)){ // 用户信息修改预查询
            int uid = Integer.parseInt(request.getParameter("userId"));
            UserDAO dao = new UserDAO();
            User user = dao.selectById(uid);
            request.setAttribute("user", user);
            request.getRequestDispatcher("manage/userUpdate.jsp")
                    .forward(request, response);
        }

    }
}



